import videojs from "video.js";
import FlvJs from "flv.js";
import { MathUtils } from "three/src/math/MathUtils";

export default class VideoUtil {
    private videoElement;

    public makeVideoElement(url) {
        let scope = this;
        this.videoElement = document.createElement('video');
        this.videoElement.crossOrigin = 'anonymous';
        this.videoElement.id = MathUtils.generateUUID();
        this.videoElement.src = url;
        this.videoElement.loop = true;
        this.videoElement.muted = true;

        this.videoElement.autoplay = true;

        let streamMsg = this.decodeStreamUrl(url);
        if (streamMsg.isStreamUrl == true) {
           if(streamMsg.isFlvType == true) {
               this.playFlvVideo(url);
           } else {
               this.playHlsVideo(url);
           }
        } else {
            //使用原生组件播放视频
            this.videoElement.play();
        }

        return this.videoElement;
    }
    
    private playHlsVideo(url) {
        //使用videojs组件播放http living stream格式的视频 m3u8,hls
        let video = videojs(this.videoElement, {
            autoplay: true,
            muted: true,
            loop: true,
            controls: false,
            preload: 'auto',
            sources: [{
                type: 'application/x-mpegURL',
                src: url
            }]
        });
        video.ready(function () {
            video.play();
        })
    }

    private playFlvVideo(url) {
        var flvPlayer = FlvJs.createPlayer({
            type: 'flv',
            url: url
        });
        flvPlayer.attachMediaElement(this.videoElement);
        flvPlayer.load();
        flvPlayer.play();
    }

    private decodeStreamUrl(url: string): {isStreamUrl: boolean, isFlvType: boolean} {
        let patten = /.hls$|.m3u8$|.flv$/i;
        let result = url.match(patten);
        let streamMsg: {isStreamUrl: boolean, isFlvType: boolean} = {isStreamUrl: false, isFlvType: false};
        streamMsg.isStreamUrl = ( !(null === result || undefined === result) );
        streamMsg.isFlvType = (result && result[0].indexOf('flv') > -1);
        return streamMsg;
    }
}